<template>
  <el-dialog title="编辑" :visible.sync="visiable" width="50%" :before-close="handleClose">
    <el-form :rules="rules" ref="formData" :model="formData" label-width="100px"  >
      <el-form-item label="歌曲名称:" prop="songName">
        <el-input v-model="formData.songName"></el-input>
      </el-form-item>
      <el-form-item label="专辑:" prop="album">
        <el-input v-model="formData.album"></el-input>
      </el-form-item>
      <el-form-item label="歌手名称:" prop="singerId">
        <el-select v-model="formData.singerId" filterable placeholder="请选择">
          <el-option
            v-for="item in allSingerList"
            :key="item.singerId"
            :label="item.singerName"
            :value="item.singerId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="歌曲分类:" prop="songCategoryId">
        <el-select v-model="formData.songCategoryId" filterable placeholder="请选择">
          <el-option
            v-for="item in allSongCategoryList"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面图" prop="songImg">
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadMainImg">
          <img v-if="formData.songImg" :src="formData.songImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="发行日期:" prop="releaseTime">
        <el-date-picker
          value-format="yyyy-MM-dd HH:mm:ss"
          type="date"
          placeholder="请选择日期"
          v-model="formData.releaseTime"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">已发布</el-radio>
          <el-radio :label="0">未发布</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="播放地址:" prop="songAddr">
        <el-input v-model="formData.songAddr"></el-input>
      </el-form-item>
      <el-form-item align="center">
        <el-button type="primary" @click="submit('formData')" >确认</el-button>
        <el-button type="danger"  @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import fileApi from "@/api/file";
import musicApi from '@/api/music';
export default {
  props:{
    id: null,  // 歌曲id
    visiable:{  // 弹出窗口
      type:Boolean,
      default:false
    },
    remoteClose: Function, // 用于关闭窗口
  },

  data() {
    return {
      allSingerList: [], // 所有的歌手信息
      allSongCategoryList: [], // 所有的歌曲分类信息
      formData: {
        songName: '',
        singerName: '',
        songImg: '',
        releaseTime: '',
        status: '',
        songAddr: '',
        songCategoryId: ''
      },
      rules: {
        songName:[
          { required: true, message: '请输入歌曲名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        singerId:[
          { required: true, message: '请选择歌手名称', trigger: 'blur' }
        ],
        songCategoryId:[
          { required: true, message: '请选择歌曲分类', trigger: 'blur' }
        ],
        releaseTime:[
          { required: true, message: '请选择发行日期', trigger: 'change' }
        ],
        status:[
          {required: true, message: '请选择是否发布', trigger: 'change'}
        ],
        songAddr:[
          { required: true, message: '请输入播放地址', trigger: 'blur' }
        ]
      }
    }
  },

  watch: {
    // 监听visiable的变化 将改变之后的值传入
    visiable(val) {
      if(val) {
        this.fetchAllSinger();
        this.fetchSongInfo();
        this.fetchAllSongCategory();
      }
    },
  },

  methods: {
    // 提交
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          musicApi.updateSong(this.formData).then(response => {
            if (response.code === 200) {
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 1500
              });
            } else if (response.code === 306) {
              this.$notify.error({
                title: '错误',
                message: '您没有操作权限，请联系管理员',
                duration: 1500
              });
            } else {
              this.$notify.error({
                title: '错误',
                message: '系统异常，请稍后再试',
                duration: 1500
              });
            }
            this.handleClose();
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 查询全部的歌曲分类
    fetchAllSongCategory() {
      musicApi.getAllSongCategory().then(response => {
        if (response.code === 200) {
          this.allSongCategoryList = response.data;
        }
      })
    },

    // 查询全部的歌手
    fetchAllSinger() {
      musicApi.getAllSinger().then(response => {
        if (response.code === 200) {
          this.allSingerList = response.data;
        }
      })
    },

    // 根据id查询歌曲信息
    fetchSongInfo() {
      musicApi.getById(this.id).then(response => {
        if (response.code === 200) {
          this.formData = response.data;
        }
      })
    },

    // 上传歌曲封面图
    uploadMainImg(file) {
      const data = new FormData();
      data.append('file', file.file);
      fileApi.uploadImage(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200) {
          this.formData.songImg = response.data;
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有上传文件权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    // 关闭窗口
    handleClose() {
      // 将表单清空
      this.$refs['formData'].resetFields();
      // 调用父组件的方法关闭窗口
      this.remoteClose();
    },
  },
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
